package org.example.http;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class HttpSessionImpl implements HttpSession {

    private String id = UUID.randomUUID().toString().replace("-", "");
    private long creationTime = System.currentTimeMillis();
    protected long lastAccessedTime;
    // 默认会话的有效期是30分钟
    private int maxInactiveInterval = 30;
    private Map<String, Object> attributes = new HashMap<String, Object>();

    // 会话容器 应该保存在应用上下文对下中
    protected static Map<String, HttpSession> sessions = new HashMap<>();

    // 构造函数
    public HttpSessionImpl() {
        // 会话容器 应该保存在应用上下文对下中
        sessions.put(id, this);
        // 会话创建时, 最后访问时间就是创建时间
        lastAccessedTime = creationTime;
    }

    @Override
    public long getCreationTime() {
        return creationTime;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public long getLastAccessedTime() {
        return lastAccessedTime;
    }

    @Override
    public int getMaxInactiveInterval() {
        return maxInactiveInterval;
    }

    @Override
    public void invalidate() {
        // 会话容器移出该会话对象
        sessions.remove(id);
        System.out.println("sessions = " + sessions);
    }

    @Override
    public void setAttribute(String name, Object value) {
        attributes.put(name, value);
    }

    @Override
    public Object getAttribute(String name) {
        return attributes.get(name);
    }

    @Override
    public void removeAttribute(String name) {
        attributes.remove(name);
    }
}
